// define 声明模块 通过require来使用一个模块
const factories = {};

// 声明模块，将模块存储在一个对象内
function define(moduleName, dependencies, factory) {
  factory.dependencies = dependencies; // 如果存在依赖的话，将依赖挂载到factory上。
  factories[moduleName] = factory;
}

// 引用模块
function require(modules, callback) {
  const reArray = modules.map((module) => {
    // 第一次调用的话 factory = function(name) {return `${name}'s gender is man`; }
    // 第二次调用的时候factories.name = function() {return 'my name';    }
    const factory = factories[module]; 
    let dependencies = factory.dependencies; //['name']
    let result;
    if (dependencies) {
      require(dependencies, function() { // 递归 ['name']
        result = factory && factory.apply(null, arguments)
      });
    } else {
        result = factory();
    }
    return result;
  }) 
  callback.apply(null, reArray);
}

define('name', [], function() {
  return 'my name';
})

define('age', [], function() {
  return 'this is age'
})

define('gender', ['name'], function(name) {
  return `${name}'s gender is man`;
})

require(['name', 'age'], function(name, age) {
  console.log(`name is: ${name}; age is: ${age}`);
})

require(['name', 'age', 'gender'], function(name, age, gender) {
  console.log(`name is: ${name}; age is: ${age}; gender is: ${gender}`);
})